/**   
 * 项目名：五位一体化工安全信息平台
 * 日期：    2019-12-10 15:29:26  
 * Copyright (c) 2015- joysuch-版权所有     
 */

package com.joysuch.wwyt.bp.service.impl;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.transaction.Transactional;

import com.google.gson.Gson;
import com.joysuch.wwyt.bp.bean.BpRiskPromiseBraodcastListBean;
import com.joysuch.wwyt.bp.bean.BpRiskPromiseBraodcastListBean.Search;
import com.joysuch.wwyt.bp.bean.MhRiskBroadcastBean;
import com.joysuch.wwyt.bp.bean.MhRiskBroadcastBean.ProductionFacilityStats;
import com.joysuch.wwyt.bp.bean.MhRiskBroadcastBean.SafetyWorkCertStats;
import com.joysuch.wwyt.bp.entity.BpRiskPromiseBraodcast;
import com.joysuch.wwyt.bp.entity.dsl.QBpRiskPromiseBraodcast;
import com.joysuch.wwyt.bp.repository.BpRiskPromiseBraodcastDao;
import com.joysuch.wwyt.bp.service.BpRiskPromiseBraodcastService;
import com.joysuch.wwyt.bp.service.BpWorkSafetyCertService;
import com.joysuch.wwyt.core.common.util.PageDataUtils;
import com.joysuch.wwyt.core.common.util.PageDataUtils.PageDataConvert;
import com.joysuch.wwyt.core.common.util.SimpleDateFormatCache;
import com.joysuch.wwyt.core.exception.BusinessRestrictionsException;
import com.joysuch.wwyt.core.repository.BaseUserDao;
import com.querydsl.core.types.Predicate;
import org.joda.time.LocalDate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

@Service
@Transactional
public class BpRiskPromiseBraodcastServiceImpl implements BpRiskPromiseBraodcastService {

    @Autowired
    private BpRiskPromiseBraodcastDao dao;
    @Autowired
    private BaseUserDao baseUserDao;
    @Autowired
    private BpWorkSafetyCertService bpWorkSafetyCertService;

    @Override
    public Page<BpRiskPromiseBraodcastListBean> findByPage(Pageable page, Search condition) {
        Predicate predicate = prepareListSearchCondition(condition);

        Page<BpRiskPromiseBraodcast> data = predicate == null ? dao.findAll(page) : dao.findAll(predicate, page);

        return PageDataUtils.convertPageData(data,
                new PageDataConvert<BpRiskPromiseBraodcastListBean, BpRiskPromiseBraodcast>() {

                    @Override
                    public BpRiskPromiseBraodcastListBean convert(BpRiskPromiseBraodcast f) {
                        BpRiskPromiseBraodcastListBean bean = new BpRiskPromiseBraodcastListBean();

                        // ID
                        bean.setId(f.getId());
                        // 公示日期
                        bean.setDate(f.getDate());
                        // 主要负责人
                        bean.setCeo(f.getCeo());
                        // 所属机构
                        bean.setOrgId(f.getOrgId());
                        // 公告内容
                        bean.setCode(f.getCode());
                        bean.setPublishUserName(baseUserDao.getBaseUserNameById(f.getCreateBy()));
                        return bean;
                    }

                });
    }

    private Predicate prepareListSearchCondition(Search condition) {
        if (condition.getDate() != null) {
            QBpRiskPromiseBraodcast braodcast = QBpRiskPromiseBraodcast.bpRiskPromiseBraodcast;
            return braodcast.date.eq(SimpleDateFormatCache.getYmd().format(condition.getDate()));
        }
        return null;
    }

    @Override
    public void delete(Long id) throws BusinessRestrictionsException {
        // 校验业务逻辑是否允许删除。如本数据被其他业务关联，删除后导致其他业务不可用。不能删除时将抛出业务异常
        checkBussinessRestrictions(id);
        dao.deleteById(id);
    }

    /**
     * 校验业务逻辑是否允许删除。如本数据被其他业务关联，删除后导致其他业务不可用
     * 
     * @param id
     *            要删除的业务ID
     * @throws BussinessRestrictionsException
     *             抛出的业务异常
     */
    private void checkBussinessRestrictions(Long id) throws BusinessRestrictionsException {

    }

    @Override
    public BpRiskPromiseBraodcast findById(Long id) {
        return dao.findById(id).get();
    }

    @Override
    public void addOrUpdate(MhRiskBroadcastBean entity) {
        BpRiskPromiseBraodcast broadcast = dao.findFirstByDate(SimpleDateFormatCache.getYmd().format(entity.getDate()));
        if (broadcast == null) {
            broadcast = new BpRiskPromiseBraodcast();
            broadcast.setCode("GG" + SimpleDateFormatCache.getYmd_Pure().format(entity.getDate()));
        }
        broadcast.setCeo(entity.getCeo());
        broadcast.setContent(toJson(entity));
        String format = SimpleDateFormatCache.getYmd().format(entity.getDate());
        broadcast.setDate(format);
        dao.save(broadcast);
    }

    private String toJson(Object entity) {
        return new Gson().toJson(entity);
    }

    @Override
    public MhRiskBroadcastBean getTodayBroadcast() {
        // 每天10-次日10点，显示今天数据
        Calendar c = Calendar.getInstance();
        if (c.get(Calendar.HOUR_OF_DAY) < 10) {
            c.add(Calendar.HOUR_OF_DAY, -10);
            // 减去10小时
        }
        BpRiskPromiseBraodcast braodcast = dao.findFirstByDate(SimpleDateFormatCache.getYmd().format(c.getTime()));
        if (braodcast == null) {
            // List<BpRiskPromiseBraodcast> list = dao.findLastest(SimpleDateFormatCache.getYmd().format(c.getTime()),
            // PageRequest.of(0, 1));
            // if (list.size() > 0) {
            // braodcast = list.get(0);
            // }
            // braodcast = new BpRiskPromiseBraodcast();
            // MhRiskBroadcastBean bean = new MhRiskBroadcastBean();
            // braodcast.setContent(null);
        }
        return braodcast == null ? defaultBroadcast()
                : new Gson().fromJson(braodcast.getContent(), MhRiskBroadcastBean.class);
    }

    private MhRiskBroadcastBean defaultBroadcast() {
        MhRiskBroadcastBean b = new MhRiskBroadcastBean();
        b.setCeo("");
        b.setPilotProduction(0);
        b.setRunning(0);
        b.setCompany("");
        b.setDate(new Date());
        b.setMhSafe(1);
        b.setProductionFacilityStats(new ProductionFacilityStats());
        b.setSafetyWorkCerts(new SafetyWorkCertStats());
        return b;
    }

    @Override
    public MhRiskBroadcastBean loadTemplate() {
        List<BpRiskPromiseBraodcast> list = dao.findLastestOne(PageRequest.of(0, 1));
        MhRiskBroadcastBean result = new MhRiskBroadcastBean();
        MhRiskBroadcastBean template = null;
        if (!list.isEmpty()) {
            template = new Gson().fromJson(list.get(0).getContent(), MhRiskBroadcastBean.class);
            result.setProductionFacilityStats(new ProductionFacilityStats());
            result.setCeo(template.getCeo());
            result.setCompany(template.getCompany());
            result.setMhSafe(template.getMhSafe());
            result.setMhSafeText(template.getMhSafeText());
            result.setPromiseContent(template.getPromiseContent());
            result.setPilotProduction(template.getPilotProduction());
        }
        // 根据当天0-24点数据，填充作业证数据
        completeWorkCertsInfo(result);
        return result;
    }

    private void completeWorkCertsInfo(MhRiskBroadcastBean result) {
        Date start = LocalDate.now().toDate();
        Date end = LocalDate.now().plusDays(1).toDate();
        // 左开右闭区间
        result.setSafetyWorkCerts(bpWorkSafetyCertService.statsInProgressionCertsBetweenTime(start, end));
    }

}
